package com.gitee.sop.layui.adminserver.entrance.resolver;


import com.gitee.sop.layui.adminserver.module.base.util.ObjectUtil;
import com.gitee.sop.layui.adminserver.plugins.cache.util.CacheUtil;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale;
import java.util.Objects;

/**
 * 自定义国际化解析器
 *
 * @author: huwei
 * @date: 2019/10/23 17:49
 * @version: 1.0.0
 */
public class CustomLocaleResolver implements LocaleResolver {

    private static final String I18N_LANGUAGE = "i18n_language";
    private static final String I18N_LANGUAGE_SESSION = "i18n_language_session";

    @Override
    public Locale resolveLocale(HttpServletRequest req) {
        String i18n_language = req.getParameter(I18N_LANGUAGE);
        Locale locale = Locale.getDefault();
        if (Objects.nonNull(i18n_language)) {
            String[] language = i18n_language.split("_");
            locale = new Locale(language[0], language[1]);
            HttpSession session = req.getSession();
            String localeJsonString = ObjectUtil.toJson(locale);
            CacheUtil.put((session.getId() + "#" + I18N_LANGUAGE_SESSION), localeJsonString, this.getClass().getName());
        } else {
            HttpSession session = req.getSession();
            String localeJson = CacheUtil.get(session.getId() + "#" + I18N_LANGUAGE_SESSION, this.getClass().getName());
            Locale localeInCache = ObjectUtil.toBean(localeJson, Locale.class);
            if (Objects.nonNull(localeInCache)) {
                locale = localeInCache;
            }
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest req, HttpServletResponse res, Locale locale) {

    }

}  